package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.itheima.entity.PageResult;
import com.itheima.mapper.MenuMapper;
import com.itheima.pojo.Menu;
import com.itheima.service.MenuService;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;


@Service(interfaceClass = MenuService.class)
public class MenuServiceImpl implements MenuService {

    @Autowired
    private MenuMapper menuMapper;

    /**
     * 通过用户名查询菜单集合
     * @param username
     * @return
     */
    @Override
    public List<Menu> queryMenuList(String username) {
       List<Menu> fatherMenuList =  menuMapper.queryFatherMenuList(username);

        //循环遍历父菜单
        for (Menu menu : fatherMenuList) {
            Integer id = menu.getId();
            //通过父菜单id查询所对应的子菜单
            List<Menu> sonMenuList =  menuMapper.querySonMenuList(id);
            menu.setChildren(sonMenuList);
        }


        return fatherMenuList;
    }



    @Override
    public List<Menu> findAllMenu() {

        List<Menu> menuList = menuMapper.findAllMenu();
        return menuList;
    }

    @Override
    public List<Integer> findMenuIdsByRoleId(Integer id) {

        return menuMapper.findMenuIdsByRoleId(id);
    }

    public void findByName(String name){
        Integer count = menuMapper.findByName(name);
        if (count>0){
            throw new RuntimeException("名称不能重复！");
        }
    }

    /**
     *  新增菜单
     */
    @Override
    public void add(Menu menu) {
        findByName(menu.getName());
        menuMapper.add(menu);
    }

    /**
     *  分页查询菜单
     */
    @Override
    public PageResult findPage(Integer currentPage, Integer pageSize, String queryString) {
        PageHelper.startPage(currentPage,pageSize);
        List<Menu> menuList = menuMapper.findPageByCondition(queryString);
        PageInfo<Menu> pageInfo = new PageInfo<>(menuList);
        return new PageResult(pageInfo.getTotal(),pageInfo.getList());
    }

    /**
     *  修改菜单
     */
    @Override
    public void update(Menu menu) {
        findByName(menu.getName());
        menuMapper.update(menu);
    }

    @Override
    public void deleteById(Integer id) {
        //判断是否被角色引用
        Integer count = menuMapper.findMenuCount(id);
        if (count>0){
            throw new RuntimeException("该菜单被用户引用不能删除！");
        }
        //判断是否是最小子菜单（最小级菜单才能删除）
        Integer count2 = menuMapper.findMenuSonCount(id);
        if (count2>0){
            throw new RuntimeException("该菜单含有子菜单不能删除！");
        }
        //删除
        menuMapper.deleteById(id);
    }

}
